package utils

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

type IdCardResponse struct {
	Data struct {
		Birthday string `json:"birthday"`
		Address  string `json:"address"`
		Sex      string `json:"sex"`
	} `json:"data"`
	Desc string `json:"desc"`
	Code int    `json:"code"`
}

func IsCheckIDCard(idcard, name string) bool {
	// 请求的URL
	apiURL := "https://qryidcard.market.alicloudapi.com/lundear/ckidcard"

	// 设置查询参数
	params := url.Values{}
	params.Add("idcard", idcard)
	params.Add("name", name)

	// 编码查询参数
	queryString := params.Encode()

	// 创建完整的请求URL
	url := fmt.Sprintf("%s?%s", apiURL, queryString)

	method := "GET"
	client := &http.Client{}
	req, err := http.NewRequest(method, url, nil)

	if err != nil {
		fmt.Println(err)
		return false
	}
	req.Header.Add("Authorization", "APPCODE 5a3213724c2342f2a32423e299925b4c")

	res, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return false
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println(err)
		return false
	}
	fmt.Println(string(body))
	// 使用结构体进行解析
	var response IdCardResponse
	err = json.Unmarshal(body, &response)
	if err != nil {
		fmt.Println("解析JSON失败:", err)
		return false
	}
	if response.Code == 0 {
		return true
	}
	return false
}
